'''
Created on May 29, 2012

@author: mupet
'''

import wx
from syslogd.gui.tabs.RuleAddWindow import RuleAddWindow
from syslogd.gui.ConfHolder import ConfHolder

class RulesTab(wx.Panel):
    
    name = "Rules"
    currentselection = -1;
    
    rules = []
    
    def onListSelection(self, event):
        self.currentselection=event.GetSelection()
        print(">>>>>>>>"+str(self.currentselection))
    
    def createUI(self, sizer):
        addButton = wx.Button(self, label='Add new rule')
        addButton.Bind(wx.EVT_BUTTON, self.addRule)
        sizer.Add(addButton, flag=wx.EXPAND, pos=(0,0))
        
        removeButton = wx.Button(self, label='remove selected rule')
        removeButton.Bind(wx.EVT_BUTTON, self.removeRule)
        sizer.Add(removeButton, flag=wx.EXPAND, pos=(0,1))
        
        self.ruleList = wx.ListBox(self, -1, style=wx.LB_HSCROLL | wx.EXPAND | wx.ALL | wx.LB_MULTIPLE)
        self.ruleList.Bind(wx.EVT_LISTBOX, self.onListSelection)
        self.showRules()
        sizer.Add(self.ruleList, flag=wx.EXPAND, pos=(1,0), span=(1,3))
        sizer.AddGrowableRow(1)
        sizer.AddGrowableCol(2)
        
    def addRule(self, event):
        frame = RuleAddWindow(None, title="Add Rule")
        frame.Show()
    
    def removeRule(self, event):
        if(self.currentselection>=0):
            for rule in ConfHolder.getInstance().getList():
                if rule.__str__() == self.ruleList.Items[self.currentselection]:
                    ConfHolder.getInstance().getList().remove(rule)
                    break
            self.showRules()
            ConfHolder.getInstance().writeConfiguration()
            
            
        
    def showRules(self):
        self.ruleList.Clear()
        for rule in ConfHolder.getInstance().getList():
            self.ruleList.Append(rule.__str__())

    def __init__(self, parent, generalEventListener):
        '''
        Constructor
        '''
        wx.Panel.__init__(self, parent)
        self.setListener(generalEventListener)
        sizer = wx.GridBagSizer(2,3)
        self.SetSizer(sizer)
        self.createUI(sizer)
        
    def setListener(self, generalEventListener):
        self.listener = generalEventListener.getGeneralTabListener()